package com.bit.net.component.data.server;

import com.bit.net.Message;
import com.bit.net.RequestCallback;
import com.bit.net.RequestContext;
import com.bit.net.Request;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.ReadTimeoutException;
import lombok.extern.slf4j.Slf4j;

/**
 * 控制中心服务处理.
 *
 * @since 2018/10/10
 */
@Slf4j
public class DataRequestChannelHandler extends SimpleChannelInboundHandler<Message> {


    private DataHandlerServiceFaced serviceFaced;

    public DataRequestChannelHandler(DataHandlerServiceFaced serviceFaced) {
        this.serviceFaced = serviceFaced;

    }

    @Override
    protected void channelRead0(final ChannelHandlerContext ctx, Message msg) throws Exception {
        log.debug("[Game request] Request:{}", msg);
        serviceFaced.handleRequest(new RequestContext().setChannel(ctx.channel()).setPayload(msg), new RequestCallback() {
            @Override
            public void callback(RequestContext requestContext) {
                System.out.println(msg + "处理完毕！");
            }
        });

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.debug("[Game client] closed, client:{}", ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

        if (cause instanceof ReadTimeoutException) {
            log.info("[Game client] idle, client:{}", ctx);
            ctx.channel().close();
            return;
        }

        log.error("[Game request] handle error", cause);

    }
}
